package com.example.demo.service.role;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.common.MyShiroRealm;
import com.example.demo.domain.role.Role;
import com.example.demo.domain.role.RoleMenu;
import com.example.demo.mapper.role.RoleMapper;
import com.example.demo.mapper.role.RoleMenuMapper;
import com.example.demo.mapper.userInfo.UserRoleMapper;

@Service("roleService")
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private RoleMenuMapper roleMenuMapper;

	@Autowired
	private UserRoleMapper userRoleMapper;

	@Override
	public int deleteByPrimaryKey(Integer roleId) {
		// TODO Auto-generated method stub
		return this.roleMapper.deleteByPrimaryKey(roleId);
	}

	@Override
	public int insert(Role record) {
		// TODO Auto-generated method stub
		roleMapper.insert(record);
		RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
		MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
		realm.clearCachedAuthorizationInfo();
		return insertRoleMenu(record);
	}

	private int insertRoleMenu(Role role) {
		// TODO Auto-generated method stub
		int rows = 1;
		// 角色与菜单关联
		List<RoleMenu> list = new ArrayList<RoleMenu>();
		for (Integer menuId : role.getMenuIds()) {
			RoleMenu rm = new RoleMenu();
			rm.setRoleId(role.getRoleId());
			rm.setMenuId(menuId);
			list.add(rm);
		}
		if (list.size() > 0) {
			rows = roleMenuMapper.batchRoleMenu(list);
		}
		return rows;
	}

	@Override
	public int insertSelective(Role record) {
		// TODO Auto-generated method stub
		return this.roleMapper.insertSelective(record);
	}

	@Override
	public Role selectByPrimaryKey(Integer roleId) {
		// TODO Auto-generated method stub
		return this.roleMapper.selectByPrimaryKey(roleId);
	}

	//修改保存角色信息
	@Override
	public int updateByPrimaryKeySelective(Role role) {
		// TODO Auto-generated method stub
		roleMapper.updateByPrimaryKey(role);
		//清除shiro的权限缓存
		RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
		MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
		realm.clearCachedAuthorizationInfo();
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
        //重新添加新的角色菜单管理
        return insertRoleMenu(role);
		
	}

	@Override
	public int updateByPrimaryKey(Role record) {
		// TODO Auto-generated method stub
		return this.roleMapper.updateByPrimaryKey(record);
	}

	// 查询角色信息
	@Override
	public List<Role> selectRoleList(Role role) {
		// TODO Auto-generated method stub
		return this.roleMapper.selectRoleList(role);
	}

	// 删除角色信息
	@Override
	public int deleteRoleByIds(String[] ids) {
		// TODO Auto-generated method stub
		//删除角色菜单的关联
		for(int i=0; i<ids.length ; i++) {
		Integer ri = Integer.parseInt(ids[i]);
		roleMenuMapper.deleteRoleMenuByRoleId(ri);
		}
		return this.roleMapper.deleteRoleByIds(ids);
	}

	// 检查角色名称唯一
	@Override
	public int checkRoleNameUnique(Role role) {
		// TODO Auto-generated method stub
		Integer id = role.getRoleId() == null ? -1 : role.getRoleId();
		Role r = roleMapper.checkRoleNameUnique(role.getRoleName());
		if (r != null && r.getRoleId() != id)
			return 1;
		return 0;
		
	}  

	@Override
	public Role checkRoleKeyUnique(Role role) {
		// TODO Auto-generated method stub
		return this.roleMapper.checkRoleKeyUnique(role.getRoleKey());
	}

	@Override
	public List<Role> selectRoleAll() {
		// TODO Auto-generated method stub
		return selectRoleList(new Role());
	}

	/**
	 * 根据用户ID查询权限
	 *
	 * @param userId
	 *            用户ID
	 * @return 权限列表
	 */
	@Override
	public Set<String> selectRoleKeys(Integer userId) {
		List<Role> perms = roleMapper.selectRolesByUserId(userId);
		Set<String> permsSet = new HashSet<>();
		for (Role perm : perms) {
			if (perm != null) {
				permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
			}
		}
		return permsSet;
	}

	/**
	 * 根据用户ID查询角色
	 *
	 * @param userId
	 *            用户ID
	 * @return 角色列表
	 */
	@Override
	public List<Role> selectRolesByUserId(Integer userId) {
		//
		List<Role> userRoles = roleMapper.selectRolesByUserId(userId);
		List<Role> roles = selectRoleAll();
		for (Role role : roles) {
			for (Role userRole : userRoles) {
				if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) {
					role.setFlag(true);
					break;
				}
			}
		}
		return roles;
	}

	// 修改角色状态
	@Override
	public int changeStatus(Role role) {
		return roleMapper.updateByPrimaryKeySelective(role);
	}

	// 查找角色是否已经被使用
	@Override
	public int countUserRoleByRoleId(Integer roleId) {
		// TODO Auto-generated method stub
		return userRoleMapper.countUserRoleByRoleId(roleId);
	}

	

}
